﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.SharePoint;
using System.Collections;
using System.Net;
using System.Threading;
using SlamCms.Common;

namespace SlamCms.SharePoint.UserManagement
{
	public class UserGroupSynchronizeModule : IHttpModule
	{
		public void Dispose()
		{
		}

		public void Init(HttpApplication context)
		{
			context.EndRequest += new EventHandler(Context_EndRequest);
		}

		protected void Context_EndRequest(object sender, EventArgs e)
		{
			HttpContext context = HttpContext.Current;

			//If postback occurs by remove button, OK button, etc on People.aspx or Aclinv.aspx, sync users
			if (!String.IsNullOrEmpty(context.Request.Form["__EVENTTARGET"]) &&
				(context.Request.Url.ToString().ToUpper().Contains("ACLINV.ASPX") ||
				 context.Request.Url.ToString().ToUpper().Contains("PEOPLE.ASPX") ||
				 context.Request.Url.ToString().ToUpper().Contains("USER.ASPX") ||
				 context.Request.Url.ToString().ToUpper().Contains("MNGSITEADMIN.ASPX")))
			{
				var uri = context.Request.Url;
				if (context.Request.UrlReferrer != null)
					uri = context.Request.UrlReferrer;

				using (SPSite site = new SPSite(uri.ToString()))
				{
					HttpWebRequest syncRequest = (HttpWebRequest)WebRequest.Create(String.Format("{0}_vti_bin/SlamCMS/UserManagementService.svc/Synchronize", site.Url.EnsureEndsWith("/")));
					syncRequest.UserAgent = context.Request.UserAgent;
					syncRequest.Credentials = CredentialCache.DefaultCredentials;
					foreach (var key in context.Request.Headers.AllKeys)
					{
						switch (key)
						{
							case "Connection":
							case "Content-Length":
							case "Date":
							case "Expect":
							case "Host":
							case "If-Modified-Since":
							case "Range":
							case "Transfer-Encoding":
							case "Proxy-Connection":
							case "Accept":
							case "Content-Type":
							case "Referer":
							case "User-Agent":
								break;
							default:
								syncRequest.Headers[key] = context.Request.Headers[key];
								break;
						}
					}
					ThreadPool.QueueUserWorkItem(c =>
					{
						syncRequest.BeginGetResponse(result => { (result.AsyncState as HttpWebRequest).EndGetResponse(result).Close(); }, syncRequest);
					});
				}
			}
		}
	}
}